#define _CRT_SECURE_NO_WARNINGS 1
#include"list.h"

void LIprint(li* p)
{
	assert(p);
	li* cur = p->next;
	while (cur != p)
	{
		printf("%d -> ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

li* LIbuycode(ldata x)
{
	li* code = (li*)malloc(sizeof(li));
	if (code == NULL)
	{
		perror("malloc fail");
		exit(1);
	}
	code->data = x;
	code->next = code->prev = code;
	return code;
}

li* LIinit()
{
	li* phead = LIbuycode(-1);
	return phead;
}

void LIdestroy(li* p)
{
	assert(p);
	li* cur = p->next;
	while (cur != p)
	{
		li* next = cur->next;
		free(cur);
		cur = next;
	}
	free(p);
	p = NULL;
}

void LIpushtail(li* p, ldata x)
{
	assert(p);
	li* newcode = LIbuycode(x);
	newcode->prev = p->prev;
	newcode->next = p;

	p->prev->next = newcode;
	p->prev = newcode;
}

void LIpushhead(li* p, ldata x)
{
	assert(p);
	li* newcode = LIbuycode(x);
	newcode->next = p->next;
	newcode->prev = p;

	p->next->prev = newcode;
	p->next = newcode;
}

void LIpoptail(li* p)
{
	assert(p && p->next != p);
	li* del = p->prev;
	del->prev->next = p;
	p->prev = del->prev;
	free(del);
	del = NULL;
}

void LIpophead(li* p)
{
	assert(p && p->next != p);
	li* del = p->next;
	p->next = del->next;
	del->next->prev = p;
	free(del);
	del = NULL;
}

li* LIfind(li* p, ldata x)
{
	li* cur = p->next;
	while (cur != p)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

void LIinsert(li* pos, ldata x)
{
	assert(pos);
	li* newcode = LIbuycode(x);
	newcode->next = pos->next;
	newcode->prev = pos;

	pos->next->prev = newcode;
	pos->next = newcode;
}

void LIerase(li* pos)
{
	assert(pos);
	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;
	free(pos);
	pos = NULL;
}
